#!/opt/miniconda3/bin/python3

from urllib import request, parse
from bs4 import BeautifulSoup
import re
import sys
import json

entry_template = '''
<h5 style="color:rgba(0,0,0,0.45);"><span>{posp}</span>&nbsp;<span>{tran}</span></h5>
<div>{def}</div>'''
example_template = '''
<div>{ex}</div>
<div style="color:rgba(0,0,0,0.45);">{tran}</div>'''

def get_value(dic, key):
    """
    :param dic: JSON object
    :param key: target key
    """
    has_found = False
    result = None
    def dfs(d, k):
        nonlocal has_found, result
        if has_found or d is None or not isinstance(d, dict):
            return
        elif key in d.keys():
            has_found = True
            result = d[key]
        else:
            for k in d.keys():
                dfs(d[k], key)
    dfs(dic,key)
    return result

url = 'http://www.iciba.com/word'
params = {'w': ' '.join(sys.argv[1:])}
querystring = parse.urlencode(params)
theurl = url + '?' + querystring
#print('request for: ' + theurl)
reqobj = request.Request(theurl, headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0"})
resp = request.urlopen(reqobj).read()
#print(resp)
soup = BeautifulSoup(resp, 'html5lib')
nextdata = json.loads(soup.find('script', id='__NEXT_DATA__').get_text())
#print(json.dumps(nextdata, indent=2))

print('<h1>{0}</h1>'.format(' '.join(sys.argv[1:])), end='')

ph = get_value(nextdata, 'symbols')
ph0 = ph[0] if ph[0] else {}
firstph = [value for name, value in ph0.items() if name in ('ph_en', 'ph_am', 'ph_other') and len(ph0[name]) > 0][0]
#titledict = {name: value for name, value in ph0.items() if name in ('ph_en', 'ph_am', 'ph_other')}
print('<div>[{0}]</div>'.format(firstph), end='')
collins = get_value(nextdata, 'collins')
if not collins:
    part = ph0['parts'][0]
    print('<div><i>{0}</i>&nbsp;<span>{1}</span></div>'.format(part['part'], '.'.join(part['means'])))
    sys.exit(0)
#print(collins[0])
entries = collins[0]['entry'] if collins[0] else {}

def print_entries(entries):
    for entry in entries:
        print(entry_template.format(**entry), end='')
        if entry['example'] and len(entry['example']) > 0:
            print('<h5 style="margin: 20px 0 5px 0;">例句</h5>', end='')
            for e in entry['example']:
                print(example_template.format(**e), end='')

print_entries(entries)
